<?php

namespace coreapi\controllers;
use common\constants\Constants;
use Yii;
use yii\web\Controller;
use yii\web\Response;

class MainController extends Controller {

   public $enableCsrfValidation = false;

   public function actionPush(){
     $this->layout= false;
     //return $this->renderPartial('@coreapi/views/main/push.php', ['model' => [],]);
     return $this->render('push', ['model' => [],]);
   }

   /**
    * 记录日志
    */
   protected function apiLog($log, $module = '') {
     $route = Yii::$app->requestedRoute;
     $log_filename = 'coreapi_trip_' . date("Y-m-d") . ".log";
     $pid = getmypid();
     $log_path = Yii::$app->params['log_path'];
     $file = $log_path . $log_filename;
     file_put_contents($file, date("Y-m-d H:i:s ") . "pid: $pid " . "router = " . $route . '  ' . $log . "\n", FILE_APPEND);
   }

	/**
	 * 执行成功，组装应答数据
	 * @param array $data 数据
	 * @param string $msg 提示信息
	 * @param int $status 状态码
	 * @return array
	 */
	protected function getSuccessArray($data = [], $msg = '请求成功', $status = Constants::STATUS_SUCCESS) {
		return \Yii::$app->utils->getSuccessArray($data, $msg, $status);
	}

	/**
	 * 执行失败，组装应答数据
	 * @param string $msg 提示信息
	 * @param int $status 状态码
	 * @param array $data 数据
	 * @return array
	 */
	protected function getFailedArray($msg = '', $status = Constants::STATUS_FAILED, $data = []) {
		return \Yii::$app->utils->getFailedArray($msg, $status, $data);
	}

	/**
	 * 返回json数据
	 * @param $data
	 * @return \yii\console\Response|Response
	 */
	protected function returnJson($data) {
		return $this->assembleAppResponse($data);
	}

	/**
	 * 返回json格式SUCESS数据
	 * @param array $data
	 * @param string $msg
	 * @param int $status
	 * @return \yii\console\Response|Response
	 */
	protected function returnSuccessJson($data = [], $msg = '请求成功', $status = Constants::STATUS_SUCCESS) {
		return $this->returnJson($this->getSuccessArray($data, $msg, $status));
	}

	/**
	 * 返回json格式FAILED数据
	 * @param string $msg
	 * @param int $status
	 * @param array $data
	 * @return \yii\console\Response|Response
	 */
	protected function returnFailedJson($msg = '', $status = Constants::STATUS_FAILED, $data = []) {
		return $this->returnJson($this->getFailedArray($msg, $status, $data));
	}

	/**
	 * 组装app端返回数据
	 * @param $params
	 * @return \yii\console\Response|Response
	 */
	private function assembleAppResponse($params) {
		\Yii::$app->response->format = Response::FORMAT_JSON;
		\Yii::$app->response->data = $params;
		return \Yii::$app->response;
	}

	/**
	 * 调试、打印变量
	 * @param mixed $res
	 */
	public function p($res) {
		if (is_string($res)) {
			echo $res . "<br />\n";
		} elseif (is_array($res)) {
			echo "<pre>\n";
			print_r($res);
			echo '</pre>\n';
		} else {
			echo "<pre>\n";
			var_dump($res);
			echo "</pre>\n";
		}
	}

}
